<template>
  <ScaleBox :width="state.windowWidth" :height="state.windowHeight" bgc="transparent" :delay="100">
    <div class="page-main" ref="pageMainRef">

      <div class="formMain">

        <div class="main-header">
          <div class="title">日间手术评估及申请单</div>
          <div class="go flex align-center" @click="goList()">
            <img class="go-img" :src="go" alt="">
            数智化日间手术管理系统
          </div>
          <div class="sn">日间序号：{{ state.serialNumber ? state.serialNumber : '未生成' }}</div>
        </div>

        <div class="main-container" v-loading="state.confirmLoading">
          <!-- 左侧 -->
          <div class="container-left">
            <!-- 就诊信息 S -->
            <div class="card-box">
              <div class="common-title">
                <span class="title">就诊信息</span>
                <span v-if="state.jzInfoConfirm" class="card-confirm">
                  <el-icon class="card-confirm-icon">
                    <ele-Select />
                  </el-icon>
                  <span class="card-confirm-txt">就诊信息已确认</span>
                </span>
                <span v-else class="card-confirm-after">
                  <el-icon class="card-confirm-icon">
                    <ele-Select />
                  </el-icon>
                  <span class="card-confirm-txt">就诊信息待确认</span>
                </span>
              </div>
              <el-form ref="patientDetailFormRef" :model="patientDetail" :rules="patientDetailRules"
                label-position="left">
                <el-row class="form-row">
                  <el-col :span="10">
                    <el-form-item label="患者姓名" prop="hzxm" inline class="form-item-border">
                      <el-input v-model="patientDetail.hzxm" placeholder="请输入患者姓名" style="width:120px"
                        size="default"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="9">
                    <el-form-item label="性别" prop="sex" inline class="form-item-border">
                      <el-radio-group v-model="patientDetail.sex" size="default">
                        <el-radio label="1">男</el-radio>
                        <el-radio label="2">女</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="5">
                    <el-form-item label="年龄" prop="age" inline class="form-item-border">
                      <el-input v-model="patientDetail.age" placeholder="请输入患者年龄" style="width:60px"
                        size="default"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row class="form-row" style="margin-top:15px;">
                  <el-col :span="10">
                    <el-form-item label="联系方式" prop="lxdh" inline class="form-item-border">
                      <el-input v-model="patientDetail.lxdh" placeholder="请输入联系方式" style="width:120px"
                        size="default"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="14">
                    <el-form-item label="身份证号" prop="sfzh" inline class="form-item-border">
                      <el-input v-model="patientDetail.sfzh" placeholder="请输入身份证号" style="width:200px"
                        size="default"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row class="form-row" style="margin-top:15px;margin-bottom:0px;">
                  <el-col :span="9">
                    <el-form-item label="就诊科室" prop="ksmc" inline class="form-item-border">
                      <el-select v-model="patientDetail.ksmc" clearable filterable remote
                        :remote-method="jzksRemoteMethod" :loading="state.departmentLoading" size="default"
                        style="width:200px">
                        <el-option v-for="item in state.departmentList" :label="item.departmentName"
                          :value="item.departmentName" @click="departmentChange(item.id)"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="就诊医生" prop="ysmc" inline class="form-item-border">
                      <el-select v-model="patientDetail.ysmc" clearable filterable remote
                        :remote-method="jzysRemoteMethod" :loading="state.doctorLoading" size="default"
                        style="width:100px">
                        <el-option v-for="item in state.doctorList" :label="item.name" :value="item.name"
                          @click="doctorChange(item.id)"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="9">
                    <el-form-item label="入院诊断" prop="zyzdmc" inline class="form-item-border">
                      <el-input v-model="patientDetail.zyzdmc" placeholder="请输入入院诊断" style="width:220px"
                        size="default"></el-input>
                    </el-form-item>
                  </el-col>

                </el-row>

              </el-form>
            </div>
            <!-- 就诊信息 E -->

            <!-- 手术信息 S -->
            <div class="card-box" style="margin-top:10px">
              <div class="common-title">
                <span class="title">手术信息</span>

                <span v-if="state.opInfoConfirm" class="card-confirm">
                  <el-icon class="card-confirm-icon">
                    <ele-Select />
                  </el-icon>
                  <span class="card-confirm-txt">手术信息已确认</span>
                </span>
                <span v-else class="card-confirm-after">
                  <el-icon class="card-confirm-icon">
                    <ele-Select />
                  </el-icon>
                  <span class="card-confirm-txt">手术信息待确认</span>
                </span>
              </div>
              <el-form ref="ruleFormRef" :model="operation_form" :rules="rules" label-position="left">
                <el-row class="form-row">
                  <el-col :span="10">
                    <el-form-item label="手术科室" prop="department" inline class="form-item-border">
                      <el-select v-model="operation_form.department" clearable filterable remote
                        :remote-method="ssksRemoteMethod" :loading="state.opDepartmentLoading"
                        @change="opDepartmentChange" size="default" style="width:230px">
                        <el-option v-for="item in state.opDepartmentList" :label="item.departmentName"
                          :value="item.id"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="入院病区" prop="hospital_area" inline class="form-item-border">
                      <el-select v-model="operation_form.hospital_area" clearable filterable @change="opAreaChange"
                        size="default" style="width:160px">
                        <el-option v-for="item in state.hospitalAreaList" :label="item.name" :value="item.id"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>

                  <el-col :span="6">
                    <el-form-item label="联系电话" prop="contact" inline class="form-item-border">
                      <el-input v-model="operation_form.contact" placeholder="请输入" size="default"
                        style="width:120px"></el-input>
                    </el-form-item>
                  </el-col>
                  <!-- <el-col :span="6">
                  <el-form-item label="术前诊断" prop="diagnosis" inline class="form-item-border">
                    <el-select v-model="operation_form.diagnosis" clearable filterable>
                      <el-option v-for="item in state.diagnosisList" :label="item.name" :value="item.code"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col> -->
                </el-row>

                <el-row class="form-row" style="margin-top:15px;">
                  <el-col :span="7">
                    <el-form-item label="主刀医生" prop="doctor" inline class="form-item-border">
                      <el-select v-model="operation_form.doctor" clearable filterable remote
                        :remote-method="zdysRemoteMethod" :loading="state.chiefDoctorLoading"
                        @change="opChiefDoctorChange" size="default" style="width:140px">
                        <el-option v-for="item in state.chiefDoctorList" :label="item.name" :value="item.id"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item label="拟行麻醉" prop="anesthesia_mode" inline class="form-item-border">
                      <el-select v-model="operation_form.anesthesia_mode" clearable filterable size="default"
                        style="width:180px">
                        <el-option v-for="item in state.anesthesiaModeList" :label="item.name"
                          :value="item.id"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="麻醉医生" prop="anesthesia" inline class="form-item-border">
                      <el-select v-model="operation_form.anesthesia" clearable filterable
                        :loading="state.anesthesiaDoctorLoading" size="default" style="width:160px">
                        <el-option v-for="item in state.anesthesiaDoctorList" :label="item.name"
                          :value="item.id"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row class="form-row form-row-no-margin" style="margin-top:15px;margin-bottom:0px;">
                  <el-col :span="20">
                    <el-form-item label="拟行手术" prop="operation" inline class="form-item-border">
                      <!-- <el-select v-model="operation_form.operation" clearable filterable
                         size="default" v-loading="state.opSelectLoading" placeholder="请通过搜索来选择拟行手术"
                        style="width:350px">
                        <el-option v-for="item in state.operationList" :label="item.name" :value="item.id"></el-option>
                      </el-select> -->
                      <el-select-v2 v-model="operation_form.operation" :options="state.operationList" clearable filterable
                        remote :remote-method="opRemoteMethod" size="default" v-loading="state.opSelectLoading"
                        placeholder="请通过搜索来选择拟行手术" style="width:350px">
                      </el-select-v2>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <!-- 手术信息 E -->

            <!-- 日间评估 S -->
            <div class="card-box daily" style="margin-top:10px">
              <div class="common-title">
                <span class="title">日间评估</span>
                <span v-if="checkConfirm" class="card-confirm">
                  <el-icon class="card-confirm-icon">
                    <ele-Select />
                  </el-icon>
                  <span class="card-confirm-txt">日间评估已确认</span>
                </span>
                <span v-else class="card-confirm-after">
                  <el-icon class="card-confirm-icon">
                    <ele-Select />
                  </el-icon>
                  <span class="card-confirm-txt">日间评估待确认</span>
                </span>
              </div>
              <div class="checked-row" v-if="state.checkedList">
                <el-checkbox-group v-model="state.checkedIds" size="large">
                  <div v-for="(item, i) in state.checkedList" :key="i">
                    <el-checkbox :label="item.id">{{
                      i + 1
                    }}.&nbsp;{{ item.text }}
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
            </div>
            <!-- 日间评估 E -->
          </div>


          <!-- 右侧 -->
          <div class="container-right">
            <div class="right-top">
              <div class="common-title">
                <span class="title">床位预约</span>
              </div>
              <div class="time-line flex ">
                <div class="time-top flex space-between align-center">
                  <el-button @click="nextOrPrevDayArr('prev')" :icon="ArrowLeftBold" size="default"
                    style="padding: 0 0 0 4px;" />
                  <div class="time-list" style="white-space: nowrap;">
                    <div class="time-item" v-for="(item, index) in state.dayArr" :key="index"
                      :class="item == state.checkedDay ? 'active' : ''" @click="changeDay(item)">
                      {{ formatValue(item) }}
                    </div>
                  </div>
                  <el-button @click="nextOrPrevDayArr('next')" :icon="ArrowRightBold" size="default"
                    style="padding: 0 0 0 4px;" />
                </div>



              </div>
            </div>

            <div class="right-bottom">
              <div class="bottom-list">
                <div class="select-box">
                  <!-- <el-select v-model="state.hospitalAreaId" placeholder="请选择病区" size="default" style="width: 150px;"
                  @change="searchBedChange">
                  <el-option v-for="(item, index) in state.hospitalAreaList" :key="index" :label="item.name"
                    :value="item.id"></el-option>
                </el-select> -->

                  <el-radio-group v-model="state.hospitalAreaId" size="default" @change="searchBedChange">
                    <el-radio-button v-for="(item, index) in state.hospitalAreaList" :key="index" :label="item.id"
                      border>{{
                        item.name }}</el-radio-button>
                  </el-radio-group>

                </div>

                <div class="bed-box" v-loading="state.bedLoading" element-loading-background="#fff">
                  <div class="bed-list">
                    <div class="bed-item flex " v-for="(item, index) in state.bedList" :key="index"
                      :class="item.patientRecord ? 'selected' : ''">

                      <!-- 如果为可选 -->
                      <div v-if="!item.patientRecord" class="item-content" :class="item.isDisable == 1?'disabled':''" @click="changeSelectBed(item)">
                        <div class="nfo-box no-user-box flex justify-center align-center">
                          <div class="no-user-center flex ">
                            <div class="bed-number">
                              {{ item.number + '床' }}
                            </div>
                            <img v-if="item.isDisable == 1" :src="lock" alt="" class="re-lock">
                            <div v-else class="re-btm">床位预约</div>
                          </div>
                        </div>
                      </div>

                      <!-- 不可选 -->
                      <div v-else class="item-content disabled">
                        <div v-if="operation_form.doctor == item.patientRecord.operation.chiefDoctorId" class="info-box">
                          <div class="bed-number">
                            {{ item.number + '床' }}
                          </div>
                          <div class="patient-infos">

                            <span class="top-line flex space-between align-center">
                              <span>{{ item.patientRecord.patient.name }}</span>
                              <span>{{ sexObj[item.patientRecord.patient.gender] }}</span>
                              <span>{{ item.patientRecord.age ? item.patientRecord.age : '-' }}</span>
                            </span>

                            <div class="flex space-between align-start" style="margin:1.5% 0;">
                              <el-tooltip class="box-item" effect="dark" :content="item.patientRecord.preDiagnosis"
                                :placement="top">
                                <span class="pre ellipsis">{{ item.patientRecord.preDiagnosis }}</span>
                              </el-tooltip>
                              <span class="flex align-center">
                                <span class="anesthesia"> {{
                                  item.patientRecord.anesthesiaAssessment &&
                                  item.patientRecord.anesthesiaAssessment.anesthesiaMode ?
                                  item.patientRecord.anesthesiaAssessment.anesthesiaMode.name : '-'
                                }}</span>
                                |
                                <span class="doctor-name ellipsis"> {{
                                  item.patientRecord.operation && item.patientRecord.operation.chiefDoctor ?
                                  item.patientRecord.operation.chiefDoctor.name : '-'
                                }}</span>
                              </span>

                            </div>
                            <el-tooltip class="box-item" effect="dark" :content="item.patientRecord.operation && item.patientRecord.operation.operation ?
                                  item.patientRecord.operation.operation.name : '-'" :placement="top">
                              <div class="operation-name ellipsis">
                                {{
                                  item.patientRecord.operation && item.patientRecord.operation.operation ?
                                  item.patientRecord.operation.operation.name : '-'
                                }}
                              </div>
                            </el-tooltip>

                          </div>
                        </div>
                        <div v-else class="info-box disabled">
                          <div class="bed-number">
                            {{ item.number + '床' }}
                          </div>
                          <img class="bed-img" :src="icon" alt="">
                        </div>
                      </div>
                    </div>
                  </div>

                </div>

              </div>
              <div class="bottom-btn flex justify-end">
                <el-button @click="confirm(ruleFormRef)" type="primary" style="padding:8px 12px;">评估完成并发起申请</el-button>
              </div>
            </div>
          </div>




        </div>
        <!-- <div class="version">
      当前版本: {{ versions.version }}
    </div> -->

      </div>
    </div>
  </ScaleBox>
</template>

<script setup name="applyForm">
import ScaleBox from "vue3-scale-box";
import { usePatientDetail } from '/@/stores/patientDetail';
import { storeToRefs } from 'pinia'
// import { useUserInfo } from '/@/stores/userInfo';

const stores = usePatientDetail();
// const userstores = useUserInfo();
const { sexObj } = storeToRefs(stores);
// const { versions } = storeToRefs(userstores);
import { applyformApi } from '/@/api/ds/apply_form'
import { toolsApi } from '/@/api/tools'

import { NextLoading } from '/@/utils/loading';
import dayjs from 'dayjs'
import { formatWeedDay } from '/@/utils/formatTime';
import { useRouter } from 'vue-router';
import icon from '/@/assets/bed-lock.png';
import go from '/@/assets/go.png';
import { throttle } from '/@/utils/toolsValidate';

const router = useRouter()
import {
  ArrowLeftBold,
  ArrowRightBold,

} from '@element-plus/icons-vue'
import { dsApi } from "/@/api/ds";
import { ElMessage, ElMessageBox } from "element-plus";
import { Session } from '/@/utils/storage';
import lock from '/@/assets/lock.png';

const step = ref("1") //步骤
const pageMainRef = ref(null);
const operation_form = ref({
  department: '',//手术科室
  hospital_area: '1',//入院病区
  diagnosis: '',//术前诊断
  operation: '',//执行手术
  doctor: '',//主刀医生
  anesthesia: "",//麻醉方式
  anesthesia_mode: "",//拟行麻醉
  contact: ""//联系方式
})
const ruleFormRef = ref({});
const patientDetailFormRef = ref({})
const patientDetail = ref({

})
const rules = reactive({
  department: [{ required: true, message: '请选择手术科室', trigger: 'change' }],
  // hospital_area: [{ required: true, message: '请选择入院病区', trigger: 'change' }],
  diagnosis: [{ required: true, message: '请选择术前诊断', trigger: 'change' }],
  operation: [{ required: true, message: '请选择执行手术', trigger: 'change' }],
  doctor: [{ required: true, message: '请选择主刀医生', trigger: 'change' }],
  anesthesia_mode: [{ required: true, message: '请选择拟行麻醉', trigger: 'change' }],
  contact: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
})
const patientDetailRules = reactive({
  hzxm: [{ required: true, message: '请输入患者姓名', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择患者性别', trigger: 'change' }],
  lxdh: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  ysmc: [{ required: true, message: '请选择就诊医生', trigger: 'change' }],
  ksmc: [{ required: true, message: '请选择就诊科室', trigger: 'change' }],
  sfzh: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
  zyzdmc: [{ required: true, message: '请选择入院诊断', trigger: 'change' }],
})
const form = reactive({
  dept: '',
  ward: '',
  diagnosis: '',
  operation: '',
  surgeon: '',
  phone: '',
  anesthesia: '',
  anesthesiologist: '',
});

const state = reactive({
  patient_record_id: '',
  bedLoading: false,
  confirmLoading: false,//确认loading

  departmentList: [], // 就诊科室
  departmentApiData: {
    search: ''
  },
  departmentLoading: false,
  opDepartmentList: [], // 手术科室
  opDepartmentApiData: {
    search: ''
  },
  opDepartmentLoading: false,
  hospitalAreaList: [],
  diagnosisList: [],
  operationApiData: {
    departmentId: null,
    doctorId: null,
    search: ''
  },
  operationList: [],
  opSelectLoading: false,
  anesthesiaModeList: [],
  hospitalAreaId: '1',
  doctorApiData: {
    chiefStatus: null,
    hospitalAreaId: null,
    departmentId: null,
    search: ''
  },
  doctorList: [],
  doctorLoading: false,
  checkedDay: null,
  dayArr: [],
  timeSlot: '上午',
  areaId: '',
  operatRoomList: [],
  bedStatus: '',
  bedList: [],
  checkedBedId: '2', // 选中的床位,

  checkedOpId: '1', //选中的台次
  operation_time: '',
  visit_doctor_id: "",
  checkedList: [],
  departmentObj: null,
  serialNumber: '',
  chiefDoctorApiData: {
    chiefStatus: 1,
    hospitalAreaId: null,
    departmentId: null,
    search: ''
  },
  chiefDoctorList: [], // 主刀医生列表
  chiefDoctorLoading: false,
  anesthesiaDoctorList: [], // 麻醉医生列表
  anesthesiaDoctorLoading: false,
  isViewAllBed: false,
  checkedIds: [],
  patientOperationAt: null,
  jzInfoConfirm: true,
  opInfoConfirm: false,
  windowWidth: 1920,
  windowHeight: 1080,
  originChiefDocId: null, // 有患者详情时的主刀id
  checkedHospitalBedId: null // 选择的床位id
});
onBeforeMount(() => {
  state.windowWidth = window.innerWidth ? window.innerWidth : 1920
  state.windowHeight = window.innerHeight ? window.innerHeight : 1080
});
// 页面加载时

onMounted(async () => {
  NextLoading.done();

  // 从url中获取数据至 patientDetail
  const queryObject = Object.keys(router.currentRoute.value.query).reduce((obj, key) => {
    obj[key.toLowerCase()] = router.currentRoute.value.query[key]
    return obj
  }, {})
  patientDetail.value = queryObject
  console.log('patientDetail', patientDetail.value)


  // 查看当前有无token 没有的话 通过医生代码YSDM 获取token
  const token = Session.get('token');
  console.log('token', token)
  if (!token) {
    const res = await applyformApi().getToken({ jobNo: router.currentRoute.value.query.YSDM ? router.currentRoute.value.query.YSDM : 10006 })
    Session.set("token", res.data.accessToken)
  }

  // 通过 医生代码YSDM来获取 visit_doctor_id
  const ress = await applyformApi().getUserIdByJobNo({ jonNo: router.currentRoute.value.query.YSDM ? router.currentRoute.value.query.YSDM : 10006 })
  if (!ress.data.uid) { // 如果获取的为空 清空
    patientDetail.value.ysmc = ''
  } else {
    state.visit_doctor_id = ress.data.uid // 就诊医生
    operation_form.value.doctor = ress.data.uid // 主刀医生
    state.operationApiData.doctorId = ress.data.uid // 根据主刀医生id获取手术

    // 联系电话
    applyformApi().getUserPhoneById({ uid: operation_form.value.doctor }).then(res => {
      operation_form.value.contact = res.data.phone
    })
  }

  // 通过科室代码 ksdm来获取科室id和科室名称
  const departmentRes = await applyformApi().getDepartmentByKSDM({ departmentNo: patientDetail.value.ksdm })
  state.departmentObj = { id: departmentRes.data.departmentId }
  operation_form.value.department = state.departmentObj.id // 手术科室默认为就诊科室
  state.chiefDoctorApiData.departmentId = state.departmentObj.id
  state.operationApiData.departmentId = state.departmentObj.id
  if (!departmentRes.data.departmentId) { // 如果获取的为空 清空
    patientDetail.value.ksmc = ''
  }

  getOption()

  try {
    const patient = await applyformApi().patientDetail({ recordID: router.currentRoute.value.query.GHXH })
    if (patient?.data?.patientId) {
      console.log("患者信息已存在")

      state.patient_record_id = patient.data.id
      state.serialNumber = patient.data.serialNumber
      if (patient.data) {
        patientDetail.value.lxdh = patient.data.patient.phone
        patientDetail.value.ksmc = patient.data.visitingDepartment ? patient.data.visitingDepartment.departmentName : ''
        patientDetail.value.ysmc = patient.data.visitingDoctor ? patient.data.visitingDoctor.name : ''

        operation_form.value.department = patient.data.operation ? patient.data.operation.departmentId : ''
        operation_form.value.hospital_area = patient.data.hospitalArea ? patient.data.hospitalArea.id : '1'
        operation_form.value.doctor = patient.data.operation ? patient.data.operation.chiefDoctorId : ''
        operation_form.value.contact = patient.data.operation ? patient.data.operation.chiefDoctorPhone : ''
        operation_form.value.operation = patient.data.operation ? patient.data.operation.operationId : ''
        operation_form.value.anesthesia = patient.data.anesthesiaAssessment ? patient.data.anesthesiaAssessment.anaesthetistId : ''
        operation_form.value.anesthesia_mode = patient.data.anesthesiaAssessment ? patient.data.anesthesiaAssessment.anesthesiaModeId : ''

        state.chiefDoctorApiData.departmentId = patient.data.operation ? patient.data.operation.departmentId : ''
        state.operationApiData.departmentId = patient.data.operation ? patient.data.operation.departmentId : ''
        state.operationApiData.doctorId = patient.data.operation ? patient.data.operation.chiefDoctorId : '' // 获取手术接口赋值
        state.hospitalAreaId = patient.data.hospitalBed ? patient.data.hospitalBed.hospitalAreaId : 1
        state.patientOperationAt = patient.data.operation ? patient.data.operation.operationAt : null
        const checkedIds = []
        if (patient.data.daytimeAssessmentItems.length) {
          patient.data.daytimeAssessmentItems.forEach(item => {
            checkedIds.push(item.id)
          })
        }
        state.checkedIds = checkedIds

        state.originChiefDocId = patient.data.operation ? patient.data.operation.chiefDoctorId : ''
        state.checkedHospitalBedId = patient.data.hospitalBedId

      }

    } else {
      //患者不存在 需要先创建患者

    }
  } catch (e) {
    console.log("出现了异常", e)

    console.log("患者信息不存在")
    let patientDetail_obj = patientDetail.value

    var post_data = {
      patient: {
        photo: null,
        name: patientDetail_obj.hzxm ?? null,//患者姓名
        gender: patientDetail_obj.sex ?? null,//性别
        identityType: 1,//身份证
        identity: patientDetail_obj.sfzh ?? null,//身份证号
        phone: patientDetail_obj.lxdh ?? null,//联系电话
        hospitalId: patientDetail_obj.hospital_id ?? null//住院号
      },
      patientRecord: {
        recordId: patientDetail_obj.ghxh,//就诊号
        visitingDoctorId: state.visit_doctor_id,//就诊医生代码
        age: patientDetail_obj.age,//年龄
        visitingDepartmentId: state.departmentObj.id,//就诊科室代码
        preDiagnosis: patientDetail_obj.zyzdmc ? patientDetail_obj.zyzdmc.trim() : '',//诊断
        hospitalAreaId: null,//病区
        hospitalBedId: null,//病床
        preDiagnosisCode: patientDetail_obj.zyzddm,
        patid: patientDetail_obj.patid,
        medicalRecordNo: patientDetail_obj.blh,
      },
    }
    applyformApi().doApply(post_data).then(res => {
      state.patient_record_id = res.data.patientRecord.id
      state.serialNumber = res.data.patientRecord.serialNumber
      state.checkedHospitalBedId = null
      ElMessage.success('创建操作成功');
    }).catch(() => {
    })
  }

  console.log('patientDetail', patientDetail)
  getDays()
  getSelectDepartments()
  getSelectOpDepartments()
  getHospitalArea()
  getDianosisList()
  getOperationList()
  getDoctorList()
  getAnesthesiaMode()

  getChiefDoctorList()
  getAnesthesiaDoctorList()


});

const getOption = () => {

  applyformApi().getOption().then(res => {
    var arr = [];
    res.data.forEach(item => {
      arr.push(item.id)
    })
    // console.log(arr)
    state.checkedList = res.data
    state.checkedIds = arr
  })
}





const searchBedChange = () => {
  getBedList()
}
const getBedList = () => {
  // state.bedLoading = true
  const apiData = {
    hospitalAreaId: state.hospitalAreaId,
    status: state.bedStatus,
    operationAt: dayjs(state.checkedDay * 1000).format('YYYY-MM-DD'),
    prid: state.patient_record_id ? state.patient_record_id : ''
  }
  toolsApi().hospitalBeds(apiData).then(res => {
    state.bedLoading = false
    state.bedList = res.data
  }).catch(() => {
    state.bedLoading = false
  })
}
const getDays = () => {
  const dayArr = []
  if (state.patientOperationAt) {
    dayArr.push(dayjs(state.patientOperationAt).startOf('day').unix())
    dayArr.push(dayjs(state.patientOperationAt).startOf('day').add(1, "days").unix())
    dayArr.push(dayjs(state.patientOperationAt).startOf('day').add(2, "days").unix())
    dayArr.push(dayjs(state.patientOperationAt).startOf('day').add(3, "days").unix())
    dayArr.push(dayjs(state.patientOperationAt).startOf('day').add(4, "days").unix())
    dayArr.push(dayjs(state.patientOperationAt).startOf('day').add(5, "days").unix())
    dayArr.push(dayjs(state.patientOperationAt).startOf('day').add(6, "days").unix())

    state.checkedDay = dayjs(state.patientOperationAt).startOf('day').unix()
  } else {
    dayArr.push(dayjs().startOf('day').unix())
    dayArr.push(dayjs().startOf('day').add(1, "days").unix())
    dayArr.push(dayjs().startOf('day').add(2, "days").unix())
    dayArr.push(dayjs().startOf('day').add(3, "days").unix())
    dayArr.push(dayjs().startOf('day').add(4, "days").unix())
    dayArr.push(dayjs().startOf('day').add(5, "days").unix())
    dayArr.push(dayjs().startOf('day').add(6, "days").unix())

    state.checkedDay = dayjs().startOf('day').unix()
  }

  state.dayArr = dayArr
  getBedList()
}

const formatValue = (value) => {
  return formatWeedDay(dayjs(value * 1000).day()) + ' ' + dayjs(value * 1000).format("MM.DD")
}

const changeDay = (value) => {
  state.checkedDay = value
  getBedList()
}

const nextOrPrevDayArr = (type) => {
  if (type == 'next') {
    const nextDayArr = []
    nextDayArr.push(state.dayArr[5] + 86400)
    nextDayArr.push(state.dayArr[5] + 86400 * 2)
    nextDayArr.push(state.dayArr[5] + 86400 * 3)
    nextDayArr.push(state.dayArr[5] + 86400 * 4)
    nextDayArr.push(state.dayArr[5] + 86400 * 5)
    nextDayArr.push(state.dayArr[5] + 86400 * 6)
    nextDayArr.push(state.dayArr[5] + 86400 * 7)
    state.dayArr = nextDayArr
    state.checkedDay = nextDayArr[0]
  } else {
    const prevDayArr = []
    prevDayArr.push(state.dayArr[0] - 86400 * 7)
    prevDayArr.push(state.dayArr[0] - 86400 * 6)
    prevDayArr.push(state.dayArr[0] - 86400 * 5)
    prevDayArr.push(state.dayArr[0] - 86400 * 4)
    prevDayArr.push(state.dayArr[0] - 86400 * 3)
    prevDayArr.push(state.dayArr[0] - 86400 * 2)
    prevDayArr.push(state.dayArr[0] - 86400)

    state.dayArr = prevDayArr
    state.checkedDay = prevDayArr[0]
  }
  getBedList()
}


// 手术信息确认
watch(
  operation_form.value,
  (val) => {
    if (val) {
      ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
          state.opInfoConfirm = true
        } else {
          state.opInfoConfirm = false
        }
      })
    }
  },
  {
    deep: true,
  }
);


// 日间评估确认
const checkConfirm = computed(() => {
  if (state.checkedIds && state.checkedIds.length > 0) {
    return true
  } else {
    return false
  }
});



const changeSelectBed = throttle((item) => {
  if (item.isDisable == 1) {
    ElMessage.warning('该床位已被管理员禁用');
    return
  }
  state.checkedHospitalBedId = item.id
  const apiData = {
    patientRecordId: state.patient_record_id,
    hospitalAreaId: state.hospitalAreaId,
    hospitalBedId: item.id,
    operationAt: dayjs(state.checkedDay * 1000).format('YYYY-MM-DD'),
  }

  dsApi().recordBed(apiData).then(res => {
    ElMessage.success('操作成功');
    getBedList()
  }).catch(() => {
    ElMessage.error(res.errMsg);
    getBedList()
  })

}, 500)

// 获取就诊科室列表
const getSelectDepartments = () => {
  state.departmentLoading = true
  toolsApi().departmentList(state.departmentApiData).then(res => {
    state.departmentLoading = false
    state.departmentList = res.data
  }).catch(() => {
    state.departmentLoading = false
  })
}

// 就诊科室远程搜索
const jzksRemoteMethod = (query) => {
  if (query) {
    state.departmentApiData.search = query
  } else {
    state.departmentApiData.search = ''
  }
  getSelectDepartments()
}

// 获取手术科室列表
const getSelectOpDepartments = () => {
  state.opDepartmentLoading = true
  toolsApi().departmentList(state.opDepartmentApiData).then(res => {
    state.opDepartmentLoading = false
    state.opDepartmentList = res.data
  }).catch(() => {
    state.opDepartmentLoading = false
  })
}


// 手术科室远程搜索
const ssksRemoteMethod = (query) => {
  if (query) {
    state.opDepartmentApiData.search = query
  } else {
    state.opDepartmentApiData.search = ''
  }
  getSelectOpDepartments()
}

// 获取医院区域
const getHospitalArea = () => {
  applyformApi().getHospitalArea().then(res => {
    state.hospitalAreaList = res.data
  })
}


// 获取诊断列表
const getDianosisList = () => {
  applyformApi().getDianosisList().then(res => {
    state.diagnosisList = res.data
  })
}

// 获取手术列表
const getOperationList = () => {
  state.opSelectLoading = true
  applyformApi().getOperationList(state.operationApiData).then(res => {
    res.data.forEach(item => {
      item.label = item.name
      item.value = item.id
    })
    state.operationList = res.data
    state.opSelectLoading = false
  }).catch(() => {
    state.opSelectLoading = false
  })
}

// 手术远程搜索
const opRemoteMethod = (query) => {
  if (query) {
    state.operationApiData.search = query
  } else {
    state.operationApiData.search = ''
  }
  getOperationList()
}

// 获取医生列表
const getDoctorList = () => {
  state.doctorLoading = true
  applyformApi().getDoctorList(state.doctorApiData).then(res => {
    state.doctorLoading = false
    state.doctorList = res.data
  }).catch(() => {
    state.doctorLoading = false
  })
}

// 就诊医生远程搜索
const jzysRemoteMethod = (query) => {
  if (query) {
    state.doctorApiData.search = query
  } else {
    state.doctorApiData.search = ''
  }
  getDoctorList()
}

// 手术信息 科室change
const opDepartmentChange = (val) => {
  if (val) {
    state.chiefDoctorApiData.departmentId = val
    state.operationApiData.departmentId = val
  } else {
    state.chiefDoctorApiData.departmentId = null
    state.operationApiData.departmentId = null
  }
  getChiefDoctorList()
  operation_form.value.doctor = ''
  operation_form.value.operation = ''
}


// 就诊科室change
const departmentChange = (val) => {
  if (val) {
    state.doctorApiData.departmentId = val
    state.departmentObj.id = val
  } else {
    state.doctorApiData.departmentId = null
    state.departmentObj.id = null
  }
  getDoctorList()
  patientDetail.value.ysmc = ''
}

// 就诊医生change
const doctorChange = (val) => {
  if (val) {
    state.visit_doctor_id = val
  } else {
    state.visit_doctor_id = null
  }
}

const opAreaChange = (val) => {
  // if (val) {
  //   state.chiefDoctorApiData.hospitalAreaId = val
  // } else {
  //   state.chiefDoctorApiData.hospitalAreaId = null
  // }
  // getChiefDoctorList()
  // operation_form.value.doctor = ''

}

const opChiefDoctorChange = (val) => {

  if (val) {
    state.operationApiData.doctorId = val
    getOperationList()

    // 联系电话
    applyformApi().getUserPhoneById({ uid: val }).then(res => {
      operation_form.value.contact = res.data.phone
    })
  } else {
    state.operationApiData.doctorId = null
    getOperationList()
  }
  operation_form.value.operation = ''
  getBedList()
}


// 获取主刀医生列表
const getChiefDoctorList = () => {
  state.chiefDoctorLoading = true
  applyformApi().getDoctorList(state.chiefDoctorApiData).then(res => {
    state.chiefDoctorLoading = false
    state.chiefDoctorList = res.data
  }).catch(() => {
    state.chiefDoctorLoading = false
  })
}

// 主刀医生远程搜索
const zdysRemoteMethod = (query) => {
  if (query) {
    state.chiefDoctorApiData.search = query
  } else {
    state.chiefDoctorApiData.search = ''
  }
  getChiefDoctorList()
}

// 获取麻醉医生列表
const getAnesthesiaDoctorList = () => {
  state.anesthesiaDoctorLoading = true
  applyformApi().getAnesthesiaDoctorList().then(res => {
    state.anesthesiaDoctorLoading = false
    state.anesthesiaDoctorList = res.data
  }).catch(() => {
    state.anesthesiaDoctorLoading = false
  })
}


// 获取麻醉方式
const getAnesthesiaMode = () => {
  applyformApi().getAnesthesiaMode().then(res => {
    state.anesthesiaModeList = res.data
  })
}


const goList = () => {
  router.push({
    path: '/dsProcess/overview'
  });
}




const confirm = (refs) => {
  if (!state.checkedHospitalBedId) {
    ElMessage.warning('请选择床位');
  } else {
    patientDetailFormRef.value.validate((valid, field) => {


      if (valid) {

        refs.validate((valid, fields) => {
          if (valid) {
            state.confirmLoading = true

            let patientDetail_obj = patientDetail.value
            let operation_form_obj = operation_form.value



            var post_data = {
              patient: {
                photo: null,
                name: patientDetail_obj.hzxm ?? null,//患者姓名
                gender: patientDetail_obj.sex ?? null,//性别
                identityType: 1,//身份证
                identity: patientDetail_obj.sfzh ?? null,//身份证号
                phone: patientDetail_obj.lxdh,//联系电话
                hospitalId: patientDetail_obj.hospital_id//住院号
              },
              patientRecord: {
                recordId: patientDetail_obj.ghxh,//就诊号
                visitingDoctorId: state.visit_doctor_id,//就诊医生代码
                age: patientDetail_obj.age,//年龄
                visitingDepartmentId: state.departmentObj.id,//就诊科室代码
                preDiagnosis: patientDetail_obj.zyzdmc ? patientDetail_obj.zyzdmc.trim() : '',//诊断
                hospitalAreaId: operation_form_obj.hospital_area,//病区
                hospitalBedId: null,//病床
                preDiagnosisCode: patientDetail_obj.zyzddm,
                patid: patientDetail_obj.patid,
                medicalRecordNo: patientDetail_obj.blh,
              },
              patientRecordOperation: {
                departmentId: operation_form_obj.department.toString(),//科室
                diagnosis: operation_form_obj.diagnosis.toString(),//诊断
                operationId: operation_form_obj.operation.toString(),//手术
                chiefDoctorId: operation_form_obj.doctor.toString(),//主刀医生
                chiefDoctorPhone: operation_form_obj.contact,//联系方式
              },
              patientRecordAnesthesiaAssessment: {
                anesthesiaModeId: operation_form_obj.anesthesia_mode,//麻醉方式
                anaesthetistId: operation_form_obj.anesthesia,//麻醉医生
              },
              daytimeAssessmentItems: state.checkedIds
            }
            if (!state.patient_record_id) {
              //当患者id 不存在 新增
              console.log("患者不存在 执行新增")
              applyformApi().doApply(post_data).then(res => {
                state.patient_record_id = res.data.patientRecord.id
                state.confirmLoading = false
                ElMessageBox.alert('申请成功', '提示', {})
                step.value = 2;
                setTimeout(() => {
                  window.location.reload()
                }, 2000);
              }).catch(() => {
                state.confirmLoading = false
              })
            } else {
              post_data.prid = state.patient_record_id
              state.confirmLoading = false
              console.log("患者存在 执行更新")
              applyformApi().updatePatient(post_data).then(res => {
                ElMessageBox.alert('申请成功', '提示', {})
                setTimeout(() => {
                  window.location.reload()
                }, 2000);
              })
            }
          } else {
            state.confirmLoading = false

            console.log('error submit!', fields)
          }
        })
      }
    })
  }


}


</script>

<style lang="scss" scoped>
.version {
  text-align: center;
  color: #999;
  margin-top: 20px;
}

.btm-card {
  :deep() {
    .el-card__body {
      padding-bottom: 40px;
    }
  }
}



.page-main {
  padding: 10px;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #F4FAFF;


  .formMain {
    width: 100%;
    height: 100%;
  }
}

.checked-row {
  margin-top: 5px;

  :deep() .el-checkbox__label {
    display: inline-grid;
    width: 100%;
    white-space: pre-line;
    word-wrap: break-word;
    line-height: 20px;
  }

  :deep() .el-checkbox.el-checkbox--large {
    height: auto !important;
    margin-bottom: 1.5%;
  }

}


.form-row {
  margin-top: 10px;
  margin-bottom: 10px;
}

.form-row-no-margin {
  margin-bottom: 0;
}

.card-confirm {
  position: relative;
  display: inline-block;
  margin-left: 20px;

  &::before {
    content: '';
    position: absolute;
    width: 15px;
    height: 15px;
    border-radius: 50%;
    background-color: #52C41A;
    top: 3px;

    /* 如果您需要同时设置::before和::after的样式，可以使用下面的方式 */
    &.confirm-before {
      background-color: rgb(86, 90, 94);
    }

    &.confirm-after {
      background-color: #52C41A;
    }
  }

  .card-confirm-txt {
    color: #52C41A;
  }
}


.card-confirm-after {
  position: relative;
  display: inline-block;
  margin-left: 20px;

  &::before {
    content: '';
    position: absolute;
    width: 15px;
    height: 15px;
    border-radius: 50%;
    background-color: rgb(86, 90, 94);
    top: 3px;
  }

  .card-confirm-txt {
    color: #666666;
  }
}


.card-confirm-icon {
  position: relative;
  display: inline-block;
  margin-right: 8px;
  left: 2px;
  top: 2px;
  color: #fff;
  font-size: 12px;
}


.main-header {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
  height: 9%;
  background: url(../../assets/form_header_bg.png) no-repeat center;
  background-size: 100% 100%;
  background-color: rgb(244, 250, 255);
  margin-bottom: 10px;

  .title {
    width: 100%;
    font-size: 32px;
    font-weight: 600;
    color: #fff;
    text-align: center;
  }

  .sn {
    position: absolute;
    right: 10px;
    bottom: 10px;
    font-size: 18px;
    color: #fff;
  }

  .go {
    position: absolute;
    left: 10px;
    bottom: 50%;
    transform: translateY(50%);
    width: 240px;
    height: 70%;
    padding: 0 10px;
    border-radius: 4px;
    font-size: 16px;
    font-weight: bold;
    color: #fff;
    cursor: pointer;
    background-color: #409EFF;

    .go-img {
      width: 20px;
      height: 20px;
      margin-right: 12px;
    }
  }
}

.main-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: calc(100% - 9% - 10px);

  .container-left {
    display: flex;
    flex-direction: column;
    width: 43.3%;
    height: 100%;
  }

  .container-right {
    width: 56%;
    height: 100%;
    background-color: #fff;

    .right-top {
      padding: 15px;
      height: 112px;
      box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.09);
    }

    .right-bottom {
      width: 100%;
      display: flex;
      flex-direction: column;
      height: calc(100% - 112px);

      .bottom-list {
        width: 100%;
        height: calc(100% - 70px);
        padding: 15px 15px 0;

      }

      .bed-box {
        width: 100%;
        height: calc(100% - 40px);
        margin-top: 8px;
      }

      .bottom-btn {
        padding: 15px;
      }
    }
  }

  .card-box {
    background-color: #fff;
    border-radius: 2px;
    padding: 15px;

    &.daily {
      display: flex;
      flex: 1;
      flex-direction: column;
      padding-bottom: 0;
    }




  }

  .common-title {
    display: flex;
    justify-content: space-between;

    .title {
      color: #000;
      font-size: 16px;
      font-weight: 500;
    }
  }
}


.time-line {
  flex-wrap: wrap;
  padding: 0px 0;
  margin-top: 15px;

  .time-top,
  .time-bottom {
    width: 100%;
  }

  .time-list {
    width: calc(100% - 120px);
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 15px;
    overflow-x: scroll;
    overflow-y: hidden;
  }

  .time-item {
    position: relative;
    height: 44px;
    text-align: center;
    line-height: 44px;
    background-color: #F9F9F9;
    color: #333;
    border-radius: 8px;
    border: 1px solid #C9C9C9;
    padding: 0 10px;
    cursor: pointer;
    font-weight: 500;


    &.active {
      color: #409EFF;
      background-color: #fff;
      border: 1px solid #409EFF;
    }

  }


}









.bed-list {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  // grid-template-rows: repeat(7, 1fr);
  gap: 0px;
  width: 100%;
  height: 100%;
  border: 0.5px solid #CECECE;

  .bed-item {
    flex-direction: column;
    // height: 74px;
    border: 0.5px solid #CECECE;
    background: #F9F9F9;
    padding: 6px;

    &.selected {
      background-color: rgba(166, 202, 240, 0.2);

    }

    .item-content {
      position: relative;
      display: flex;
      flex-direction: column;
      height: 100%;
      cursor: pointer;

      &.disabled {
        cursor: no-drop;
      }

      .no-user-box {
        position: relative;
        width: 100%;
        height: 100%;

        .no-user-center {
          position: absolute;
          left: 50%;
          transform: translateX(-50%);
          top: 0;
          flex-direction: column;

          .bed-number {
            color: #000;
            font-weight: 500;
            text-align: center;
          }

          .re-btm {
            width: 88px;
            height: 28px;
            background: #FFFFFF;
            border-radius: 2px;
            border: 1px dashed #D9D9D9;
            text-align: center;
            line-height: 26px;
            margin-top: 2%;
            color: #666;
          }
        }
      }

      .info-box {
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;

        &.disabled {
          cursor: no-drop;
        }

        .bed-img {
          width: 35px;
          height: 35px;
        }

        .bed-number {
          position: absolute;
          right: -8px;
          top: -8px;
          width: 51px;
          height: 18px;
          background: #0077D7;
          box-shadow: 0px 2px 4px 0px rgba(26, 79, 0, 0.13);
          border-radius: 11px 0px 11px 11px;
          color: #fff;
          font-size: 12px;
          text-align: center;
        }

        .patient-infos {
          width: 100%;
          height: 100%;
          font-size: 12px;

          .pre {
            width: 49%;
          }

          .anesthesia {
            display: inline-block;
            max-width: 40px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .top-line {
            width: 60%;
          }


        }
      }
    }



  }
}
</style>
